<?php

/**
 * @brief   商品模块服务层
 * @version 1.0
 * @since   2024-6-28
 */

namespace app\admin\service;

use app\admin\model\Algorithm;
use app\admin\model\Images as ImagesModel;
use app\admin\model\ProductRelation;
use app\common\ExcelService;
use app\common\SkuGenerator;
use app\facade\Basic;
use think\facade\Db;
use app\admin\model\Product as ProductModel;
use app\admin\model\Inventory as InventoryModel;
use app\admin\model\ProductDiscount as ProductDiscountModel;
use think\Exception;

class Product extends BaseService
{

    /**
     * 获取商品列表
     * @param $param
     * @param $page
     * @param $limit
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList($param = [], $page = 1, $limit = 10)
    {

        $where = [['is_del', '=', 0]];
        $arrData = ['code' => 0, 'message' => 'success'];
        if ($param['cname']) {
            $where[] = ['cname', 'like', '%' . $param['cname'] . '%'];
        }
        if ($param['sku']) {
            $where[] = ['sku', 'like', '%' . $param['sku'] . '%'];
        }
        if ($param['code']) {
            $where[] = ['code', 'like', '%' . $param['code'] . '%'];
        }
        if ($param['status']) {
            $where[] = ['status', '=', $param['status']];
        }

        if ($param['brand']) {
            $where[] = ['brand', '=', $param['brand']];
        }

        if ($param['model_id']) {
            $where[] = ['model_id', '=', $param['model_id']];
        }

        if ($param['category']) {
            $where[] = ['category', '=', $param['category']];
        }
        if (!is_null($param['billing_weight'])) {
            $where[] = ['billing_weight', $param['billing_weight'] == 1 ? '>' : '=', 0.0];
        }


        if ($param['abbr']) {
            $where[] =  ['abbr', 'like', '%' . $param['abbr'] . '%'];
        }

        if ($param['model']) {
            $where[] = ['model_id', '=', $param['model']];
        }
        if ($param['type']) {
            $where[] = ['type', '=', $param['type']];
        }

        $oProductModel = ProductModel::where($where);

        // 处理 is_merge_product 参数
        if (isset($param['is_merge_product'])) {
            $relationModel = new ProductRelation();
            $pids = $relationModel->where('is_del', 0)->column('pid');

            if ($param['is_merge_product'] == 1) {
                $oProductModel = $oProductModel->whereIn('id', $pids);
            } elseif ($param['is_merge_product'] == 0) {
                $oProductModel = $oProductModel->whereNotIn('id', $pids);
            }
        }

        // 处理 is_have_inventory 参数
        if (isset($param['is_have_inventory'])) {
            // 获取有库存的商品ID
            $productIds = Db::name('inventory')
                ->where('is_del', 0)
                ->where(function ($query) {
                    $query->whereRaw('(available_qty - lock_qty) > 0')
                        ->whereOr('allow_zero_stock_sale', 1);
                })
                ->group('productid')
                ->column('productid');

            if ($param['is_have_inventory'] == 1) {
                $oProductModel = $oProductModel->whereIn('id', $productIds);
            } elseif ($param['is_have_inventory'] == 0) {
                $oProductModel = $oProductModel->whereNotIn('id', $productIds);
            }
        }

        if ($param['algorithm']) {
            $oProductModel = $oProductModel->whereRaw('FIND_IN_SET(?, algorithm)', [$param['algorithm']]);
        }

        $total = $oProductModel->count();
        $result = $oProductModel
            ->with(['creator', 'get_category_value', 'get_brand_value', 'model_value' => function ($query) {
                return $query->field('id,model_name');
            }])
            ->append(['condition_text', 'is_advance_text', 'unit_value'])
            ->order('id', 'desc')
            ->page($page, $limit)
            ->select();

        foreach ($result as &$value) {
            $value->brand_value = $value->brand_value ?? '';
            if (isset($value->model_value)) {
                $value->model_value = $value->model_value->model_name;
            } else {
                $value->model_value = '';
            }

            $ProductModel = new ProductModel();
            /* 电源 */
            if ($value->has_powersource) {
                $has_powersource = $ProductModel->getAttributes('has_powersource');
                $value->has_powersource_name = array_key_exists($value->has_powersource, $has_powersource) ? $has_powersource[$value->has_powersource] : '';
            } else {
                $value->has_powersource_name = '';
            }

            /* 电源线 */
            if ($value->has_powerline) {
                $has_powerline = $ProductModel->getAttributes('has_powerline');
                $value->has_powerline_name = array_key_exists($value->has_powerline, $has_powerline) ? $has_powerline[$value->has_powerline] : '';
            } else {
                $value->has_powerline_name = '';
            }

            /* 规格 */
            if ($value->powerline_standards) {
                $powerline_standards = $ProductModel->getAttributes('powerline_standards');
                $value->powerline_standards_name = array_key_exists($value->powerline_standards, $powerline_standards) ? $powerline_standards[$value->powerline_standards] : '';
            } else {
                $value->powerline_standards_name = '';
            }

            if ($value->algorithm) {
                $algorithmArray = $this->getEnum(['field' => 'algorithm'])['data']['algorithm'];
                $algorithmArray = array_column($algorithmArray, null, 'value');

                $value->algorithm = array_map('intval', explode(',', $value->algorithm));
                $value->algorithm_text = array_map(function ($id) use ($algorithmArray) {
                    return isset($algorithmArray[$id]) ? $algorithmArray[$id]['label'] : null;
                }, $value->algorithm);
            }
        }
        $arrData['data'] = ['list' => $result->toArray(), 'total' => $total];
        return $arrData;
    }

    /**
     * 删除单条或多条商品数据
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete($param)
    {
        $where = [['is_del', '=', '0'], ['id', 'in', $param['ids']]];
        $oProductModel = ProductModel::where($where);
        $product = $oProductModel->find();

        if (!$product) {
            return ['code' => 1, 'message' => '获取商品信息失败！'];
        }

        Db::startTrans();
        try {
            $result = $oProductModel->update(['is_del' => time()]);
            $productAccessoriesResult = Db::name('product_accessories')
                ->whereIn('product_id', $param['ids'])
                ->update(['status' => 0, 'update_time' => date('Y-m-d H:i:s')]);
            // 提交事务
            Db::commit();
            $this->clearCTerminalCache(6); // 清除C端产品缓存
            $this->logger->logOperation($param['ids'], 'Product', '删除', '删除单条或多条商品数据');
            return ['code' => 0, 'message' => '删除商品成功！'];
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => 1, 'message' => '删除商品失败！'];
        }
    }
    /**
     * 删除单条或多条商品数据
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function hasPowerline($param)
    {
        $where = [['is_del', '=', '0'],['type', '=', 1], ['id', 'in', $param['ids']]];
        $oProductModel = ProductModel::where($where);
        $products = $oProductModel->select();

        if (!$products) {
            return ['code' => 1, 'message' => '获取商品信息失败！'];
        }
        $data = ['not_powerline' =>[],'not_powersource'=>[]];
        foreach ($products as $product ){
            if($product['has_powersource'] === 0){
                $data['not_powersource'][] = [
                    'sku' =>$product->sku,
                    'cname' =>$product->cname,
                    'id' =>$product->id,
                    'abbr' =>$product->abbr,
                    'code' =>$product->code,
                ];
            }
            if($product['has_powerline'] === 0){
                $data['not_powerline'][] = [
                    'sku' =>$product->sku,
                    'cname' =>$product->cname,
                    'id' =>$product->id,
                    'abbr' =>$product->abbr,
                    'code' =>$product->code,
                ];
            }
        }
        return ['code' => 0, 'message' => '成功！','data' =>$data];
    }

    /**
     * 添加商品
     * @param $param
     * @return array|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function create($data)
    {


        $model = new ProductModel();
        $exists = $model->where('is_del', 0)->where(function ($query) use ($data) {
            $query->where('cname', $data['cname'])->whereOr('code', $data['code']);
        })->find();
        if ($exists) {
            return ['code' => 200001, 'message' => '商品名称或编码重复'];
        }


        $data['type'] = 1;
        $generator = new SkuGenerator();
        $data['sku'] = $generator->generateSku($data['type']);

        $data['creator'] = $data['operator_id'];
        $data['create_time'] = date('Y-m-d H:i:s');
        if (isset($data['main_photo']) && $data['main_photo']) {
            $data['main_photo'] = implode(',', $data['main_photo']);
        }
        if (isset($data['photo']) && $data['photo']) {
            $data['photo'] = implode(',', $data['photo']);
        }
        if (isset($data['algorithm']) && $data['algorithm']) {
            $data['algorithm'] = implode(',', $data['algorithm']);
        }
        if ((!isset($data['billing_weight']) || !$data['billing_weight']) && $data['package_size'] && $data['gross_weight']) {
            $size = explode('*', $data['package_size']);
            $_weight = $size[0] * $size[1] * $size[2] / 5000000;
            $data['billing_weight'] = $_weight > $data['gross_weight'] ? $_weight : $data['gross_weight'];
        }
        // 开始事务
        $model->startTrans();
        try {
            $res = $model->save($data); // 执行插入
            $this->clearCTerminalCache(6); // 清除C端产品缓存
            $this->logger->logOperation($res, 'Product', '添加', '添加商品信息');

            if ($res) {
                $model->commit();
                return ['code' => 0, 'message' => '操作成功'];
            } else {
                $model->rollback();
                return ['code' => 500001];
            }
        } catch (\Throwable $th) {
            $model->rollback();
            return ['code' => 500001, 'message' => '服务器内部错误：' . $th->getMessage()];
        }
    }

   public function exportProduct()
   {
       // 1. 构建查询条件
       $where = [['is_del', '=', 0]]; // 排除已删除商品

       // 2. 查询数据并关联必要模型
       $products = ProductModel::with([
           'getBrandValue',       // 品牌名称
           'getCategoryValue',    // 分类名称
           'modelValue',       // 矿机型号
           'getParentName'        // 父商品名称
       ])
           ->where($where)
           ->select();

       // 3. 准备枚举映射（直接从模型属性获取）
       $enumMaps = [
           'unit' => (new ProductModel())->getAttributes('unit') ?? [],
           'freight_tag' => (new ProductModel())->getAttributes('freight_tag') ?? [],
           'comput_unit' => (new ProductModel())->getAttributes('comput_unit') ?? [],
           'has_powersource' =>(new ProductModel())->getAttributes('has_powersource') ?? [],
           'has_powerline' => (new ProductModel())->getAttributes('has_powerline') ?? [],
           'powerline_standards' =>(new ProductModel())->getAttributes('powerline_standards') ?? [],
           'algorithm' => (new Algorithm())->getAttributes('algorithm') ?? [],
           'condition' => ['0' => '否', '1' => '是'],
           'is_advance' => ['0' => '否', '1' => '是'],
           'status' => ['0' => '下架', '1' => '上架'],
           'type' => ['1' => '商品', '2' => '配件']
       ];

       // 4. 处理数据并格式化为导出结构
       $exportData = [];
       foreach ($products as $product) {
           $algorithmValue = [];
           if($product->algorithm){
               $algorithm = explode(',',$product->algorithm);
               foreach ($algorithm as $valuea){
                   $algorithmValue[] = $enumMaps['algorithm'][$valuea] ?? $valuea;
               }
           }

           $exportData[] = [
               $product->id,
               $product->sku,
               $product->cname,
               $product->abbr,
               $product->code,
               $product->style_code,
               $product->category_value ?? '',
               $product->brand_value ?? '',
               $product->color_specs,
               $enumMaps['condition'][$product->condition] ?? $product->condition,
               $product->expiration_date,
               $product->hashrate,
               $enumMaps['comput_unit'][$product->computing_unit] ?? $product->computing_unit,
               $product->power,
               $product->weight,
               $product->gross_weight,
               $product->billing_weight,
               $product->dimensions,
               $product->gross_dimensions,
               $product->volume,
               $enumMaps['freight_tag'][$product->freight_tag] ?? $product->freight_tag,
               $product->model_value->model_name ?? '',
               $product->describe,
               $product->remark,
               $product->min_num,
               $product->estimated_ship_date,
               $product->cost,
               $product->sales_rate,
               $product->sales_price_futures,
               $product->sales_price,
               $product->freight_price,
               $enumMaps['is_advance'][$product->is_advance] ?? $product->is_advance,
               $product->advance_ratio . '%',
               $product->create_time,
               $product->update_time,
               $enumMaps['status'][$product->status] ?? $product->status,
               $enumMaps['type'][$product->type] ?? $product->type,
               $product->parentName->cname ?? '',
               $enumMaps['unit'][$product->unit] ?? $product->unit,
               $enumMaps['has_powersource'][$product->has_powersource] ?? $product->has_powersource,
               $enumMaps['has_powerline'][$product->has_powerline] ?? $product->has_powerline,
               $product->powerline_specs,
               $enumMaps['powerline_standards'][$product->powerline_standards] ?? $product->powerline_standards,
               $product->memory_size,
               $product->chip_number,
               $product->working_mode,
               implode(',',$algorithmValue),
               $product->working_voltage,
               $product->noise_level,
               $product->network_conn_method,
               $product->operation_temperature,
               $product->working_humidity,
               $product->colling_method,
               $product->bare_macheine_size,
               $product->package_size,
               $product->free_shipping ? '是' : '否',
               $product->apply_rules ? '是' : '否',
               $product->contain_battery ? '是' : '否',
               $product->has_magnetic ? '是' : '否'
           ];
       }

       // 5. 设置Excel标题头
       $header = [
           "ID", "SKU", "商品名称", "商品简称", "商品编码", "款式编码", "分类", "品牌",
           "颜色及规格", "是否二手机", "保修期(天)", "算力", "算力单位", "功耗(w)",
           "裸机净重(kg)", "毛重(kg)", "计费重量(kg)", "裸机尺寸", "带包装尺寸",
           "体积", "运费标记", "矿机型号",  "描述", "备注",
           "最小起购量", "预计发货(天)", "成本", "销售汇率", "期货价格", "销售价",
           "运费金额", "支持预付款", "预付款比率",  "创建时间",
           "更新时间", "状态", "类型", "父商品", "单位", "含电源", "含电源线",
           "电源线规格", "电源线标准", "内存(GB)", "芯片数量", "工作模式", "支持算法",
           "工作电压", "噪音水平", "网络连接", "工作温度", "工作湿度", "制冷方式",
           "裸机尺寸(mm)", "包装尺寸(mm)", "是否包邮", "应用物流规则", "含电池", "带磁性"
       ];

       // 6. 导出Excel
       ExcelService::export($exportData, $header, '商品导出_' . date('YmdHis') . '.xlsx');
   }
    /**
     * @describe
     * @author: Bobo
     * @date: 2025-04-08 16:30:16
     * @param [type] @required
     * @return Renderable
     */
    public function update($condation, $data)
    {

        $model = new ProductModel();
        $exists = $model->where('is_del', 0)->where('id', '<>', $condation['id'])->find();

        if ($exists && isset($data['cname']) && isset($data['code'])) {
            if ($exists->cname == $data['cname'] || $exists->code == $data['code']) {
                return ['code' => 200001, 'message' => '商品名称或编码重复'];
            }
        }
        if (isset($data['main_photo']) && $data['main_photo']) {
            $data['main_photo'] = implode(',', $data['main_photo']);
        }
        if (isset($data['photo']) && $data['photo']) {
            $data['photo'] = implode(',', $data['photo']);
        }
        if (isset($data['algorithm']) && $data['algorithm']) {
            $data['algorithm'] = implode(',', $data['algorithm']);
        }
        if ((!isset($data['billing_weight']) || !$data['billing_weight']) && isset($data['package_size']) && isset($data['gross_weight']) && $data['package_size'] && $data['gross_weight']) {
            $size = explode('*', $data['package_size']);
            $_weight = $size[0] * $size[1] * $size[2] / 5000000;
            $data['billing_weight'] = $_weight > $data['gross_weight'] ? $_weight : $data['gross_weight'];
        }

        $res = $this->getInfo($condation);
        $res = $res['data'];
        $res['main_photo'] = implode(',', $res['main_photo']);
        $res['photo'] = implode(',', $res['photo']);
        $update_data = [];
        $legal_fields = array_keys($model->schema);

        foreach ($data as $key => $value) {
            if (in_array($key, $legal_fields) &&  $res[$key] !== $value) {
                $update_data[$key] = $value;
                if ($update_data[$key] === '' || $update_data[$key] === null) {
                    $update_data[$key] = null;
                }
            }
        }


        $update_data['updater'] = $data['operator_id'];
        $update_data['update_time'] = date('Y-m-d H:i:s');
        $model->startTrans();
        try {
            $res = $model->where('is_del', 0)->where($condation)->update($update_data);
            $this->clearCTerminalCache(6); // 清除C端产品缓存
            $this->logger->logOperation($res, 'Product', '修改', '修改商品信息');

            if ($res > -1) {
                $model->commit();
                return ['code' => 0, 'message' => '操作成功'];
            } else {
                $model->rollback();
                return ['code' => 500001];
            }
        } catch (\Throwable $th) {
            $model->rollback();
            return ['code' => 500001, 'message' => '服务器内部错误：' . $th->getMessage()];
        }
    }

    /**
     * 获取单个商品信息`
     * @param int $id 商品ID
     * @return array
     */
    public function getInfo($param)
    {
        $where = [['is_del', '=', '0'], ['id', '=', $param['id']]];
        $product = ProductModel::where($where)->with(['creator', 'get_category_value', 'get_brand_value', 'model_value' => function ($query) {
            return $query->field('id,model_name');
        }])->append(['condition_text', 'is_advance_text'])->find();

        // $currencyArr = [];
        // $currencyNameArr = [];
        //     if ($product->get_currency) {
        //     foreach ($product->get_currency as $item) {
        //         $currencyArr[] = $item->currencyid . '';
        //         $currencyNameArr[] = $item->name;
        //     }
        // }
        // $product->currency = $currencyArr;
        // $product->currency_text = implode(',', $currencyNameArr);
        // unset($product->get_currency);


        if (isset($product->model_value)) {
            $product->model_value = $product->model_value->model_name;
        } else {
            $product->model_value = '';
        }


        $ProductModel = new ProductModel();
        /* 电源 */
        if ($product->has_powersource) {
            $has_powersource = $ProductModel->getAttributes('has_powersource');
            $product->has_powersource_name = array_key_exists($product->has_powersource, $has_powersource) ? $has_powersource[$product->has_powersource] : '';
        } else {
            $product->has_powersource_name = '';
        }

        /* 电源线 */
        if ($product->has_powerline) {
            $has_powerline = $ProductModel->getAttributes('has_powerline');
            $product->has_powerline_name = array_key_exists($product->has_powerline, $has_powerline) ? $has_powerline[$product->has_powerline] : '';
        } else {
            $product->has_powerline_name = '';
        }

        /* 规格 */
        if ($product->powerline_standards) {
            $powerline_standards = $ProductModel->getAttributes('powerline_standards');
            $product->powerline_standards_name = array_key_exists($product->powerline_standards, $powerline_standards) ? $powerline_standards[$product->powerline_standards] : '';
        } else {
            $product->powerline_standards_name = '';
        }
        // 处理算法
        if ($product->algorithm) {
            $algorithmArray = $this->getEnum(['field' => 'algorithm'])['data']['algorithm'];
            $algorithmArray = array_column($algorithmArray, null, 'value');
            $product->algorithm = array_map('intval', explode(',', $product->algorithm));
            $product->algorithm_text = array_map(function ($id) use ($algorithmArray) {
                return isset($algorithmArray[$id]) ? $algorithmArray[$id]['label'] : null;
            }, $product->algorithm);
        } else {
            $product->algorithm_text = [];
        }

        // 处理商品图片信息
        $formatPhoto = [];
        $formatPhoto_ids = [];
        if ($product->photo) {
            $oImagesModel = ImagesModel::whereIn('id', explode(',', $product->photo))->select();
            foreach ($oImagesModel as $key => $item) {
                $formatPhoto[] = [
                    'id' => $item->id,
                    'url' => $item->url
                ];
                $formatPhoto_ids[] = $item->id;
            }
        }
        $product->photo = $formatPhoto_ids;
        $product->photo_urls = $formatPhoto;

        $mainPhoto = [];
        $mainPhoto_ids = [];
        if ($product->main_photo) {
            $oImagesModel = ImagesModel::where('id', $product->main_photo)->find();
            if ($oImagesModel) {  // 添加空值检查
                $mainPhoto[] = [
                    'id' => $oImagesModel->id,
                    'url' => $oImagesModel->url
                ];
                $mainPhoto_ids[] = $oImagesModel->id;
            }
        }
        $product->main_photo = $mainPhoto_ids;
        $product->main_photo_urls = $mainPhoto;

        unset($product->get_inventory);

        if (!$product) {
            return ['code' => 1, 'message' => '获取商品信息失败！'];
        }

        // 获取关联配件
        $accessoriesIds = Db::name('product_accessories')
            ->alias('a')
            ->join('product p', 'a.accessories_id = p.id')
            ->where([
                'a.product_id' => $param['id'],
                'a.status' => 1,
                'p.type' => 2,
            ])
            ->column('accessories_id as id ,code, p.cname,p.status');
        if (0 !== count($accessoriesIds)) {
            $product['product_accessories_linked_data'] = $accessoriesIds;
        } else {
            $product['product_accessories_linked_data'] = [];
        }

        $product = $product->toArray();
        return ['code' => 0, 'message' => 'success', 'data' => $product];
    }


    /**
     * 针对用户下单时获取商品库存列表 展示库存信息仓库等信息
     * @param $param
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getInventoryList($param = [], $page = 1, $limit = 10)
    {
        $inventoryWhere = [['qty', '>', 0], ['db_inventory.is_del', '=', 0]];
        $productWhere = [];
        if ($param['name']) {
            $productWhere[] = ['cname', 'like', '%' . $param['name'] . '%'];
        }

        $oInventoryModel = InventoryModel::withJoin([
            'product' => function ($query) use ($param, $productWhere) {
                $query->where($productWhere);
            },
        ])->with([
            'get_warehouse_name' => function ($query) {
                return $query->field(['id', 'name']);
            },
            'discount' => function ($query) {
                return $query->field('id,inventoryid,num,rate,price');
            },
            'product' => function ($query) {
                return $query->with([
                    'getBrand' => function ($query) {
                        return $query->field('id,name,image');
                    },
                    'getCategory' => function ($query) {
                        return $query->field('id,name');
                    }
                ]);
            }
        ])->where($inventoryWhere)->paginate($limit);
        $arrData['data'] = $oInventoryModel->toArray();
        return $arrData;
    }

    /**上架商品
     * @param int $id 商品ID
     * @return bool
     * @date 2024-6-28
     */
    public function onsale($id)
    {
        $where = [['is_del', '=', '0'], ['id', '=', $id]];
        $product = $this->productModel->where($where)->find();
        if (!$product) {
            return ['code' => 0, 'message' => '获取商品信息失败！'];
        }
        if ($product->save(['status' => 1])) {
            $this->logger->logOperation($id, 'Product', '上架', '上架商品');
            return ['code' => 1, 'message' => '上架商品成功！'];
        } else {
            return ['code' => 0, 'message' => '上架商品失败！'];
        }
    }

    /**下架商品
     * @param int $id 商品ID
     * @return bool
     * @date 2024-6-28
     */
    public function offsale($id)
    {
        $where = [['is_del', '=', '0'], ['id', '=', $id]];
        $product = $this->productModel->where($where)->find();
        if (!$product) {
            return ['code' => 0, 'message' => '获取商品信息失败！'];
        }
        if ($product->save(['status' => 0])) {
            $this->logger->logOperation($id, 'Product', '下架', '下架商品');
            return ['code' => 1, 'message' => '下架商品成功！'];
        } else {
            return ['code' => 0, 'message' => '下架商品失败！'];
        }
    }

    public function discount($param)
    {
        $oProductDiscountModel = ProductDiscountModel::whereIn('inventoryid', $param['ids'])->select();
        $formatData = [];
        foreach ($oProductDiscountModel as $item) {
            $formatData[$item->inventoryid][$item->num] = $item->price;
        }
        return ['code' => 0, 'message' => 'success', 'data' => $formatData];
    }

    public function formatDiscount($param, $productid, $inventoryid, $wid, $futures = false)
    {
        $discount = [];
        foreach ($param as $k => $jer) {
            if ($k != 'sales_price' && $k != 'sales_price_futures') {
                for ($i = 1; $i <= 5; $i++) {
                    // 判断层级
                    if ($jer['param1'] == $i) {
                        $type = $jer['type'];
                        $value = $jer['value'];

                        // 初始化 param1 分组
                        if (!isset($discount[$i])) {
                            $discount[$i] = [];
                        }

                        // 将 value 值添加到对应的 type 中
                        $discount[$i][$type] = $value;
                        $discount[$i]['level'] = $jer['param1'];
                    }
                }
            }
        }

        foreach ($discount as &$value) {
            $value['productid'] = $productid;
            $value['inventoryid'] = $inventoryid;
            $value['wid'] = $wid;

            if ($futures) {
                $value['price'] = $value['discounted_sales_price_futures'] ?? 0;
            } else {
                $value['price'] = $value['discounted_sales_price'] ?? 0;
            }
            unset($value['discounted_sales_price_futures']);
            unset($value['discounted_sales_price']);
        }

        return $discount;
    }

    public function getFieldEnum($field)
    {
        $model = new ProductModel();
        $res = $model->getFieldEnum($field);

        return [
            'code' => 0,
            'data' => $res
        ];
    }

    /**
     *   获取枚举
     */
    public function getEnum($param)
    {
        $modelSeller = new ProductModel();
        $result = $modelSeller->getFieldEnumBynew($param['field']);
        return Basic::data(0, 'ok', $result);
    }
}
